from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from .serializers import RegisterSerializer

# 1. 注册   POST /api/register
@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    ser = RegisterSerializer(data=request.data)
    ser.is_valid(raise_exception=True)
    user = ser.save()
    return Response({
        'status':200,
        'data': {
            'msg': '注册成功', 
            'id': user.id}
            }, 
        status=status.HTTP_201_CREATED)

# 2. 登录   POST /api/login
@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    username = request.data.get('username')
    password = request.data.get('password')
    user = authenticate(username=username, password=password)
    if user is None:
        return Response({
            'status': 400,
            'data': {
                'msg': '用户名或密码错误'
            }
        }, status=status.HTTP_400_BAD_REQUEST)
    refresh = RefreshToken.for_user(user)
    return Response({
        'status': 200,
        'data': {
            'msg': '登录成功',
            'access': str(refresh.access_token),
            'refresh': str(refresh),
        }
    }, status=status.HTTP_200_OK)

# 3. 用户信息  GET /my/userinfo  （需 token）
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_info(request):
    user = request.user
    return Response({
        'status': 200,
        'data': {
            'msg': '获取用户信息成功',
            'info': {
                'id': user.id,
                'username': user.username,
            }
        }
    }, status=status.HTTP_200_OK)

# 4. 退出登录  POST /my/logout
@api_view(['POST'])
@authentication_classes([])  # 明确禁用所有认证
@permission_classes([AllowAny])  # 明确允许所有访问
def logout(request):
    try:
        # 简单的退出登录，前端清除token即可
        # 不需要认证，因为退出登录主要是前端行为
        return Response({
            'status': 200,
            'data': {
                'msg': '退出登录成功'
            }
        }, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({
            'status': 400,
            'data': {
                'msg': '退出登录失败'
            }
        }, status=status.HTTP_400_BAD_REQUEST)